# app/api/v1/family/ai_project.py
import logging
from typing import Optional
from fastapi import APIRouter, Body, Query, Path,Depends, Request
from tortoise.expressions import Q

from app.controllers.system.aiprojects import ai_project_controller
from app.schemas.system.aiprojects import *
from app.utils.request import RequestHandler
from app.utils.app_log import logger
from app.core.auth import get_current_user_required,get_current_superuser
from app.schemas.base.login import JWTPayload

router = APIRouter()

@router.get("/list", summary="获取AI项目列表")
async def get_ai_projects(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    name: Optional[str] = Query(None, description="项目名称，用于搜索"),
    type: Optional[str] = Query(None, description="项目类型"),
    difficulty: Optional[int] = Query(None, description="难度等级"),
    current_user: JWTPayload = Depends(get_current_superuser)
):
    """获取AI项目列表"""
    try:
        q = Q(is_deleted=False)
        if name:
            q &= Q(name__contains=name)
        if type:
            q &= Q(type=type)
        if difficulty is not None:
            q &= Q(difficulty=difficulty)

        total, data = await ai_project_controller.project_list(page=page, page_size=page_size, q=q)
        return RequestHandler.success_paginated(data=data, total=total, page=page, page_size=page_size)
    except Exception as e:
        logger.error(f"获取AI项目列表失败: {str(e)}")
        return RequestHandler.server_error(message="获取AI项目列表失败")

@router.get("/{project_id}", summary="获取AI项目详情")
async def get_ai_project(
    project_id: int = Path(..., description="项目ID"),
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """获取AI项目详情"""
    try:
        project_info = await ai_project_controller.get_project_info(project_id, current_user.user_id)
        return RequestHandler.success(data=project_info)
    except Exception as e:
        logger.error(f"获取AI项目详情失败: {str(e)}")
        return RequestHandler.server_error(message="获取AI项目详情失败")

@router.delete("/{project_id}", summary="删除AI项目")
async def delete_ai_project(
    project_id: int = Path(..., description="项目ID"),
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """删除AI项目"""
    try:
        delete_result = await ai_project_controller.remove_project(project_id, current_user.user_id)
        if delete_result:
            return RequestHandler.success(message="AI项目删除成功")
    except Exception as e:
        logger.error(f"删除AI项目失败: {str(e)}")
        return RequestHandler.server_error(message="删除AI项目失败")

@router.post("/create", summary="创建AI项目")
async def create_ai_project(
    project_in: AIProjectCreate,
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """创建AI项目"""
    try:
        logger.info(f"创建AI项目: {project_in.name}")
        project_in.user_id = current_user.user_id
        project = await ai_project_controller.create_project(project_in)
        if project:
            return RequestHandler.success(message="AI项目创建成功", data={"id": project.id})
    except Exception as e:
        logger.error(f"创建AI项目失败: {str(e)}")
        return RequestHandler.server_error(message="创建AI项目失败")

@router.put("/{project_id}", summary="更新AI项目")
async def update_ai_project(
    project_id: int = Path(..., description="项目ID"),
    project_in: AIProjectUpdate = None,
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """更新AI项目"""
    try:
        if project_in:
            project_in.id = project_id
        project = await ai_project_controller.update_project_info(project_id, project_in, current_user.user_id)
        if project:
            return RequestHandler.success(message="AI项目更新成功")
    except Exception as e:
        logger.error(f"更新AI项目失败: {str(e)}")
        return RequestHandler.server_error(message="更新AI项目失败")

@router.put("/{project_id}/views", summary="增加项目浏览量")
async def increase_project_views(
    project_id: int = Path(..., description="项目ID"),
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """增加项目浏览量"""
    try:
        # current_user.family_id
        project = await ai_project_controller.increase_views(project_id, 1)
        if project:
            return RequestHandler.success(message="浏览量增加成功")
    except Exception as e:
        logger.error(f"增加项目浏览量失败: {str(e)}")
        return RequestHandler.server_error(message="增加项目浏览量失败")

@router.put("/{project_id}/star", summary="收藏/取消收藏项目")
async def toggle_project_star(
    project_id: int = Path(..., description="项目ID"),
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """收藏/取消收藏项目"""
    try:
        # current_user.family_id
        project = await ai_project_controller.toggle_star(project_id, 1)
        action = "收藏" if project.stars > 0 else "取消收藏"
        return RequestHandler.success(message=f"项目{action}成功")
    except Exception as e:
        logger.error(f"收藏项目失败: {str(e)}")
        return RequestHandler.server_error(message="收藏项目失败")